//
//  FunctionListVC.m
//  Stream
//
//  Created by shaw on 16/8/1.
//  Copyright © 2016年 showshaw. All rights reserved.
//

#import "FunctionListVC.h"
#import "FunctionItem.h"
#import "FunctionTableViewCell.h"
@interface FunctionListVC ()<UITableViewDelegate,UITableViewDataSource,FunctionTableViewCellDelegate>
@property (nonatomic,strong) UITableView* tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)NSMutableArray *savedData;
@end

@implementation FunctionListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"关注";
    
    //
    [self setupView];
    
    //load for net
    [self loadData];
}

//加载数据
-(void)loadData
{
    NSString * apiURL = [Utils BaseUrlOfApi:@"category-list"];
    
    // mapping
    [FunctionItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID" : @"id"
                 };
    }];
    [FunctionGroup mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID" : @"id"
                 };
    }];
    [FunctionGroup mj_setupObjectClassInArray:^NSDictionary *{
        return @{
                 @"lumps" : @"FunctionItem"
                };
    }];
    
    [XXNetRequest POST:apiURL
                params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                    if ([responseObject[@"code"] integerValue] == NetRequestStatusSuccess) {
                        NSArray * data = responseObject[@"result"];
                        self.dataArray = [FunctionGroup mj_objectArrayWithKeyValuesArray:data];
                        [self.tableView reloadData];
                    }
                } fail:^(NSURLSessionDataTask *task, NSError *error) {
                    [MBProgressHUD showError:@"网络连接错误"];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
}


-(void)setupView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 50.0f;
    
    [_tableView registerNib:[UINib nibWithNibName:@"FunctionTableViewCell" bundle:nil] forCellReuseIdentifier:@"FunctionTableViewCell"];
    [self.view addSubview:_tableView];
    
}
#pragma mark - init tableview

-(NSMutableArray*)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}

#pragma mark - TableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [[self.dataArray[section] lumps] count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString* identity = @"FunctionTableViewCell";
    FunctionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    
    FunctionGroup * funcGroup = self.dataArray[indexPath.section];
    FunctionItem * item = funcGroup.lumps[indexPath.row];

    item.focused = NO;
    
    [self.savedData enumerateObjectsUsingBlock:^(FunctionItem* obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.name isEqualToString:item.name]) {
            item.focused = YES;
        }
    }];
    
    cell.item = item;
    return cell;
}


//Cell 显示之前
-(void)tableView:(UITableView *)tableView willDisplayCell:(FunctionTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
//    FunctionGroup * funcGroup = self.dataArray[indexPath.section];
//    FunctionItem * item = funcGroup.lumps[indexPath.row];
//    
//    [self.savedData enumerateObjectsUsingBlock:^(FunctionItem* obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if ([obj.name isEqualToString:item.name]) {
//            cell.focusStatus = YES;
//        }
//        else{
//            cell.focusStatus = NO;
//        }
//    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.0f;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W_, 30.0f)];
    headerView.backgroundColor = [UIColor whiteColor];
    
    
    UIView* dividerView = [[UIView alloc] init];
    dividerView.backgroundColor = RGBColor(51, 149, 250, 1);
    [headerView addSubview:dividerView];
    [dividerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@2);
        make.left.equalTo(headerView).offset(12);
        make.centerY.equalTo(headerView);
    }];
    
    UILabel * label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = RGBColor(45, 45, 45, 45);
    
    [headerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(dividerView.mas_right).offset(5);
        make.centerY.equalTo(headerView);
    }];
    
    [dividerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_top);
        make.bottom.equalTo(label.mas_bottom);
    }];
    
    
    FunctionGroup * funcGroup = self.dataArray[section];
    label.text = funcGroup.name;
    
    return headerView;
}

#pragma  mark - TableViewCell Delegate
-(void)functionTableViewCellDidClickFucusButton:(FunctionTableViewCell *)cell
{
    if (cell.item.isFocused) { //之前已经关注，取消关注
        [self.savedData enumerateObjectsUsingBlock:^(FunctionItem*obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name isEqualToString:cell.item.name]) {
                [self.savedData removeObject:obj];
            }
        }];
        cell.item.focused = NO;
    }
    else{       //没关注，添加关注
        [self.savedData addObject:cell.item];
        cell.item.focused = YES;
    }
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView reloadRowsAtIndexPaths:@[
                                             [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]
                                             ] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Lazy initialization
-(NSMutableArray *)savedData
{
    if (_savedData == nil) {
        _savedData = [NSMutableArray arrayWithArray:[CacheTool loadUserFunctionCategory]];
    }
    return _savedData;
}
//页面关闭时，同步缓存并且发送通知
-(void)viewWillDisappear:(BOOL)animated
{
    if([CacheTool saveUserFunctionCategory:self.savedData])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kUserFunctionCategoryChange object:nil];
    }
    
    [super viewWillDisappear:animated];
}


@end
